<!-- 客户管理 -->
<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-card shadow="never" class="mb-4">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="queryString">
          <el-input
            v-model="queryParams.queryString"
            placeholder="客户名称/统一社会信用代码"
            clearable
            style="width: 250px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="全部状态"
            clearable
            style="width: 120px"
          >
            <el-option label="激活" value="active" />
            <el-option label="停用" value="suspended" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 客户列表 -->
    <el-card shadow="never">
      <div class="flex justify-between items-center mb-4">
        <div class="flex items-center">
          <el-button
            type="primary"
            icon="Plus"
            @click="handleOpenDialog()"
          >
            新增客户
          </el-button>
          <el-button
            type="danger"
            icon="Delete"
            :disabled="selectIds.length === 0"
            @click="handleDelete()"
          >
            批量删除
          </el-button>
        </div>
        <div class="text-sm text-gray-500">
          共 {{ total }} 条记录
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="pageData"
        @selection-change="handleSelectionChange"
        stripe
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="客户名称" prop="name" min-width="200" show-overflow-tooltip />
        <el-table-column label="统一社会信用代码" prop="creditCode" width="200" show-overflow-tooltip />
        <el-table-column label="联系人" prop="contact" width="120" />
        <el-table-column label="联系电话" prop="contactPhone" width="150" />
        <el-table-column label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag
              :type="scope.row.status === 'active' ? 'success' : 'danger'"
              size="small"
            >
              {{ scope.row.status === 'active' ? '激活' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="站点数量" width="100" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="handleViewSites(scope.row)"
            >
              {{ scope.row.sites?.length || 0 }} 个
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createdAt" width="180" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              link
              icon="Edit"
              @click="handleOpenDialog(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="success"
              link
              icon="View"
              @click="handleViewSites(scope.row)"
            >
              站点
            </el-button>
            <el-dropdown @command="(command) => handleCommand(command, scope.row)">
              <el-button type="primary" link>
                更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    :command="scope.row.status === 'active' ? 'suspend' : 'activate'"
                  >
                    {{ scope.row.status === 'active' ? '停用' : '激活' }}
                  </el-dropdown-item>
                  <el-dropdown-item command="delete" divided>
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="flex justify-end mt-4">
        <el-pagination
          v-model:current-page="queryParams.currentPage"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 客户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="handleCloseDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="140px"
      >
        <el-form-item label="客户名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入客户名称" />
        </el-form-item>
        <el-form-item label="统一社会信用代码" prop="creditCode">
          <el-input 
            v-model="formData.creditCode" 
            placeholder="请输入18位统一社会信用代码" 
            maxlength="18"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="联系人" prop="contact">
          <el-input v-model="formData.contact" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input 
            v-model="formData.contactPhone" 
            placeholder="请输入11位手机号码" 
            maxlength="11"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input
            v-model="formData.address"
            type="textarea"
            :rows="3"
            placeholder="请输入详细地址"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCloseDialog">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 站点列表对话框 -->
    <el-dialog
      v-model="sitesDialogVisible"
      title="客户站点列表"
      width="800px"
    >
      <div v-if="currentCustomerSites.length === 0" class="text-center py-8 text-gray-500">
        该客户暂无站点
      </div>
      <el-table v-else :data="currentCustomerSites" stripe>
        <el-table-column label="站点名称" prop="name" />
        <el-table-column label="站点地址" prop="address" show-overflow-tooltip />
        <el-table-column label="创建时间" prop="createdAt" width="180" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import CustomerAPI from '@/api/system/customer.api.js'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const sitesDialogVisible = ref(false)
const submitLoading = ref(false)
const selectIds = ref([])
const total = ref(0)
const pageData = ref([])
const currentCustomerSites = ref([])
const formRef = ref()

// 查询参数
const queryParams = reactive({
  currentPage: 1,
  pageSize: 10,
  queryString: '',
  status: ''
})

// 表单数据
const formData = reactive({
  id: null,
  name: '',
  creditCode: '',
  contact: '',
  contactPhone: '',
  address: '',
  remark: ''
})

// 表单校验规则
const formRules = {
  name: [
    { required: true, message: '请输入客户名称', trigger: 'blur' }
  ],
  creditCode: [
    { required: true, message: '请输入统一社会信用代码', trigger: 'blur' },
    { 
      pattern: /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/, 
      message: '统一社会信用代码格式不正确，请输入18位有效的统一社会信用代码', 
      trigger: 'blur' 
    }
  ],
  contact: [
    { required: true, message: '请输入联系人', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { 
      pattern: /^1[3-9]\d{9}$/, 
      message: '请输入11位有效的手机号码', 
      trigger: 'blur' 
    }
  ]
}

// 计算属性
const dialogTitle = computed(() => {
  return formData.id ? '编辑客户' : '新增客户'
})

// 方法
const handleQuery = async () => {
  loading.value = true
  try {
    // 过滤掉空字符串的参数
    const params = { ...queryParams }
    if (!params.status || params.status === '') {
      delete params.status
    }
    if (!params.queryString || params.queryString === '') {
      delete params.queryString
    }
    
    const res = await CustomerAPI.getPage(params)
    // request.js 已经处理了响应，直接返回 data
    pageData.value = res.records || []
    total.value = res.total || 0
  } catch (error) {
    console.error('查询客户列表失败:', error)
    ElMessage.error('查询失败')
    pageData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

const handleResetQuery = () => {
  queryParams.queryString = ''
  queryParams.status = ''
  queryParams.currentPage = 1
  handleQuery()
}

const handleSelectionChange = (selection) => {
  selectIds.value = selection.map(item => item.id)
}

const handleOpenDialog = (row) => {
  if (row) {
    Object.assign(formData, row)
  } else {
    Object.assign(formData, {
      id: null,
      name: '',
      creditCode: '',
      contact: '',
      contactPhone: '',
      address: '',
      remark: ''
    })
  }
  dialogVisible.value = true
}

const handleCloseDialog = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
}

const handleSubmit = async () => {
  const valid = await formRef.value?.validate()
  if (!valid) return

  submitLoading.value = true
  try {
    const api = formData.id ? CustomerAPI.update : CustomerAPI.create
    await api(formData)
    ElMessage.success(formData.id ? '更新成功' : '添加成功')
    dialogVisible.value = false
    handleQuery()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

const handleDelete = async () => {
  if (selectIds.value.length === 0) {
    ElMessage.warning('请选择要删除的客户')
    return
  }

  try {
    await ElMessageBox.confirm('确定要删除选中的客户吗？', '提示', {
      type: 'warning'
    })
    await Promise.all(selectIds.value.map(id => CustomerAPI.delete(id)))
    ElMessage.success(`成功删除 ${selectIds.value.length} 个客户`)
    handleQuery()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleCommand = async (command, row) => {
  switch (command) {
    case 'activate':
    case 'suspend':
      await handleChangeStatus(row.id, command === 'activate' ? 'active' : 'suspended')
      break
    case 'delete':
      await handleDeleteOne(row.id)
      break
  }
}

const handleChangeStatus = async (id, status) => {
  try {
    await CustomerAPI.changeStatus(id, status)
    ElMessage.success('状态更新成功')
    handleQuery()
  } catch (error) {
    console.error('状态更新失败:', error)
    ElMessage.error('状态更新失败')
  }
}

const handleDeleteOne = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该客户吗？', '提示', {
      type: 'warning'
    })
    await CustomerAPI.delete(id)
    ElMessage.success('删除成功')
    handleQuery()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleViewSites = async (row) => {
  try {
    const res = await CustomerAPI.getCustomerSites(row.id)
    currentCustomerSites.value = res || []
    sitesDialogVisible.value = true
  } catch (error) {
    console.error('获取站点列表失败:', error)
    ElMessage.error('获取站点列表失败')
  }
}

const handleSizeChange = (val) => {
  queryParams.pageSize = val
  queryParams.currentPage = 1
  handleQuery()
}

const handleCurrentChange = (val) => {
  queryParams.currentPage = val
  handleQuery()
}

const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  handleQuery()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style> 